import 'package:add_2_calendar/add_2_calendar.dart';
import 'package:flutter/material.dart';
import 'todo_item.dart'; // 引入ToDoItem定义

class ToDoListScreen extends StatefulWidget {
  const ToDoListScreen({super.key});

  @override
  _ToDoListScreenState createState() => _ToDoListScreenState();
}

class _ToDoListScreenState extends State<ToDoListScreen> {
  List<ToDoItem> items = [];

  void _addItem(String title, bool isRemind, DateTime remindTime, String remindType) {
    final newItem = ToDoItem(
      id: DateTime.now().toString(),
      title: title,
      isRemind: isRemind,
      remindTime: remindTime,
      remindType: remindType,
    );
    setState(() {
      items.add(newItem);
    });
    if (isRemind) {
      _addToCalendar(newItem);  // 如果需要提醒，添加到系统日历
    }
  }

  void _deleteItem(String id) {
    setState(() {
      items.removeWhere((item) => item.id == id);
    });
  }

  void _editItem(ToDoItem item) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('编辑待办事项'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              TextField(
                onChanged: (value) {
                  item.title = value;
                },
                decoration: InputDecoration(hintText: '待办事项标题'),
              ),
            ],
          ),
          actions: <Widget>[
            TextButton(
              child: Text('取消'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            TextButton(
              child: Text('保存'),
              onPressed: () {
                setState(() {
                  _addToCalendar(item);
                });
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  void _addToCalendar(ToDoItem item) {
    if (item.remindTime != null) {
      final Event event = Event(
        title: item.title,
        description: '待办事项提醒',
        startDate: item.remindTime!,
        endDate: item.remindTime!.add(const Duration(hours: 1)),
        allDay: false,
      );

      Add2Calendar.addEvent2Cal(event).then((success) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(success ? '已添加到日历' : '添加到日历失败'),
            duration: const Duration(seconds: 2),
          ),
        );
      });
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('提醒时间未设置，未能添加到日历'),
          duration: const Duration(seconds: 2),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('待办事项列表'),
        automaticallyImplyLeading: false,
      ),
      body: ListView.builder(
        itemCount: items.length,
        itemBuilder: (context, index) {
          final item = items[index];
          return ListTile(
            title: Text(item.title),
            subtitle: Text('提醒: ${item.isRemind ? '是' : '否'}, 类型: ${item.remindType}'),
            trailing: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                IconButton(
                  icon: const Icon(Icons.edit),
                  onPressed: () => _editItem(item), // 编辑待办事项
                ),
                IconButton(
                  icon: const Icon(Icons.delete),
                  onPressed: () => _deleteItem(item.id), // 删除待办事项
                ),
              ],
            ),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _showAddDialog(),
        child: const Icon(Icons.add),
      ),
    );
  }

  void _showAddDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        String title = '';
        bool isRemind = false;
        DateTime? remindTime;
        String remindType = '单次';
        List<String> remindTypes = ['单次', '每天', '每周', '每月', '每年'];
        String buttonText = '选择提醒时间'; // 初始按钮文本

        return AlertDialog(
          title: const Text('添加新待办事项', style: TextStyle(fontWeight: FontWeight.bold)),
          content: SingleChildScrollView(
            child: StatefulBuilder(  // 使用 StatefulBuilder
              builder: (BuildContext context, StateSetter setState) {  // 提供局部 setState
                return Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: TextField(
                        onChanged: (value) {
                          title = value;
                        },
                        decoration: const InputDecoration(
                          labelText: '待办事项标题',
                          border: OutlineInputBorder(),
                        ),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          const Text('需要提醒:'),
                          Switch(
                            value: isRemind,
                            onChanged: (bool value) {
                              setState(() {
                                isRemind = value;
                              });
                            },
                          ),
                        ],
                      ),
                    ),
                    if (isRemind) Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: ElevatedButton(
                        onPressed: () async {
                          final DateTime? pickedDate = await showDatePicker(
                            context: context,
                            initialDate: remindTime ?? DateTime.now(),
                            firstDate: DateTime.now(),
                            lastDate: DateTime(2100),
                          );
                          if (pickedDate != null) {
                            final TimeOfDay? pickedTime = await showTimePicker(
                              context: context,
                              initialTime: TimeOfDay.fromDateTime(remindTime ?? DateTime.now()),
                            );
                            if (pickedTime != null) {
                              setState(() {
                                remindTime = DateTime(
                                  pickedDate.year,
                                  pickedDate.month,
                                  pickedDate.day,
                                  pickedTime.hour,
                                  pickedTime.minute,
                                );
                                // 更新按钮文本以显示选定的日期和时间
                                buttonText = '提醒时间: ${pickedDate.year}-${pickedDate.month}-${pickedDate.day} ${pickedTime.hour}:${pickedTime.minute}';
                              });
                            }
                          }
                        },
                        style: ElevatedButton.styleFrom(
                          foregroundColor: Colors.white, primary: Colors.blue,
                        ),
                        child: Text(buttonText),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 8.0),
                      child: DropdownButton<String>(
                        isExpanded: true,
                        value: remindType,
                        icon: const Icon(Icons.arrow_downward),
                        elevation: 16,
                        style: const TextStyle(color: Colors.deepPurple),
                        underline: Container(
                          height: 2,
                          color: Colors.deepPurpleAccent,
                        ),
                        onChanged: (String? newValue) {
                          setState(() {
                            remindType = newValue!;
                          });
                        },
                        items: remindTypes.map<DropdownMenuItem<String>>((String value) {
                          return DropdownMenuItem<String>(
                            value: value,
                            child: Text(value),
                          );
                        }).toList(),
                      ),
                    ),
                  ],
                );
              },
            ),
          ),
          actions: <Widget>[
            TextButton(
              child: const Text('取消', style: TextStyle(color: Colors.red)),
              onPressed: () {
                Navigator.of(context). pop();
              },
            ),
            TextButton(
              child: const Text('添加', style: TextStyle(fontWeight: FontWeight.bold)),
              onPressed: () {
                if (title.isNotEmpty && remindTime != null) {
                  setState(() {
                    _addItem(title, isRemind, remindTime!, remindType);
                  });
                  Navigator.of(context).pop();
                } else {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(
                      content: Text('请输入标题和提醒时间'),
                      duration: Duration(seconds: 2),
                    ),
                  );
                }
              },
            ),
          ],
        );
      },
    );
  }

}